﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PrimeraAFantasyFootballl.Models;

namespace PrimeraAFantasyFootballl.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        UsuarioRepository usuariorepository = new UsuarioRepository();
        EquipoRepository equiporepository = new EquipoRepository();
        EquipoController equipos = new EquipoController();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {

                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
        

            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {

            
       
            
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                

                if (createStatus == MembershipCreateStatus.Success)
                {
                    
                    Usuario us = new Usuario();
                    us.EquipoID = 3;
                    us.Username = model.UserName;
                    us.Password = model.Password;
                    us.Correo = model.Email;
                    us.Nombre = "completar";
                    us.Apellido = "completar";
                    us.Pais = "completar";
                    us.Direccion = "completar";
                    us.Comuna = "completar";
                    us.Region = 1;
                    DateTime sfa = new DateTime(2010, 12, 12);
                    us.FechaNacimiento = sfa;
                    char a = Convert.ToChar("-");
                    us.Genero = a;
                    UpdateModel(us);
                    usuariorepository.Add(us);
                    usuariorepository.Save();
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Create","Equipo");

                    

                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {


                    usuariorepository.GetUsuario(User.Identity.Name).Password=model.NewPassword;
                    usuariorepository.Save();

                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        //
        // GET: /Account/Delete

        public ActionResult Delete()
        {
            return View();

        }

        //
        // POST: /Account/Delete

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(FormCollection collection)
        {

            Usuario usuario = usuariorepository.GetUsuario(User.Identity.Name);
            Equipo equipo = equiporepository.GetEquipo(usuario.EquipoID);
            equiporepository.Delete(equipo);
            equiporepository.Save();
            System.Web.Security.Membership.DeleteUser(User.Identity.Name);
            FormsService.SignOut();
            

            return RedirectToAction("Index", "Home");

        }

    }
}
